package com.sihai.ehr.service.impl;

import com.sihai.core.*;
import com.sihai.ehr.model.biz.*;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.service.ResignService;
import com.sihai.ehr.web.pojo.StaffSearchPojo;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("resignService")
public class ResignServiceImpl implements ResignService {

    @Resource
    private DataAccessor dataAccessor;

    @Override
    public LimitedList<EmployeeinfoWork> searchResignEmployeeinfo(StaffSearchPojo search, Long organizationId, String state, Limit limit, Sorter sorter) {
        String hql = "from EmployeeinfoWork e where e.cancel='0' and e.baseId.state=? ";
        if (search == null) {
            return dataAccessor.findByHql(EmployeeinfoWork.class, hql, new Object[]{state}, limit, sorter);
        }

        Organization organization = null;
        boolean isReadTopOrg = false;
        if (search.getDepartment() > 0) {
            try {
                organization = dataAccessor.get(Organization.class, search.getDepartment());
                if (organization.getTopOrganization() == null) {
                    isReadTopOrg = true;
                }
            } catch (Exception e) {
                return null;
            }
        }
        if (search.getDepartment() < 0) {
            return dataAccessor.findByHql(EmployeeinfoWork.class, hql, new Object[]{state}, limit, sorter);
        } else if (search.getDuty() < 0) {
            return dataAccessor.findByHql(EmployeeinfoWork.class,
                    hql + (isReadTopOrg ? "and (e.organization.topOrganization.id=" + search.getDepartment() + " or e.organization.id=?)" : " and e.organization.id=?"), new Object[]{state, search.getDepartment()}, limit, sorter);
        } else {
            return dataAccessor.findByHql(EmployeeinfoWork.class,
                    hql + (isReadTopOrg ? "and (e.organization.topOrganization.id=" + search.getDepartment() + " or e.organization.id=?)" : " and e.organization.id=?") + " and e.duty.id=?",
                    new Object[]{state, search.getDepartment(), search.getDuty()}, limit,
                    sorter);
        }
    }

    @Override
    public LimitedList<EmployeeinfoBase> searchEmployeeinfo(EmployeeinfoBase baseinfo, Limit limit, Sorter sorter) {
        if (baseinfo == null) {
            String hql = "from EmployeeinfoBase e where e.cancel='0' and e.state='2'";
            return dataAccessor.findByHql(EmployeeinfoBase.class, hql, null, limit, sorter);
        }
        return null;
    }
}
